import { isObject } from '@/utils/types.js'

export default {
	inheritAttrs: false,
  props: {
    // v-model/value 绑定值
    value: {
      default: null
    },
    // 字段信息
    field: {
      type: Object,
      required: true
    },
    // 字段展示名(不传则取默认值)
    label: {
      type: String,
      default: null
    },
    // 提示信息(不传则取默认值)
    placeholder: {
      type: String,
      default: null
    },
    // 是否禁止编辑
    disabled: {
      type: Boolean,
      default: false
    },
    // 私有配置参数
    config: {
      type: Object,
      default: null
    },
    index: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      formValue: null
    }
  },
	mounted() {
		if (this.field.defaultValue && this.$isEmpty(this.formValue)) {
			// this.$emit('input', this.field.defaultValue)

			this.emitChangeEvt(this.formatDefaultValue())
		}
    console.log(this.field, 'this.field', true)
	},
  computed: {
    // 输入提示
    _placeholder() {
			if (this.field.autoGeneNumber == 1) return '根据编号规则自动生成，支持手动输入'
			return this.$isEmpty(this.placeholder) ? `请输入${this.field.name}` : this.placeholder
    },
    // 字段展示名
    _label() {
      if (this.label !== null) return this.label
      return this.field.name
    }
  },
	watch: {
		value: {
			handler(val) {
				// console.log('change value: ', val)
				this.formValue = this.value
			},
			deep: true,
			immediate: true
		},
		// #ifdef MP-WEIXIN
		// 小程序需要在这里重新赋值
		field: {
			handler() {
				this.formValue = this.field.value
			},
			deep: true,
			immediate: true
		}
		// #endif
	},
	methods: {
		emitChangeEvt(val) {
			this.$emit('input', val)
			this.$emit('change', {
				index: this.index,
				field: this.field,
				value: val
			})
		},

		/**
		 * 格式化默认值
		 */
		formatDefaultValue() {
			const defaultValue = this.field.defaultValue
			switch (this.field.formType) {
				case 'select':
					return this.getSelectDefaultVal(defaultValue)
				case 'checkbox':
					return this.getSelectDefaultVal(defaultValue)
				case 'detail_table':
					return [defaultValue]
			}
			return defaultValue
		},

		/**
		 * 获取选项类型的默认值
		 * @param {Object} data
		 */
		getSelectDefaultVal(data) {
			return data.map(o => {
				if (isObject(o)) return o
				const setting = this.field.setting
				if (setting.includes('其他') && !setting.includes(o)) {
					return {
						label: '其他',
						value: o
					}
				}
				return {
					label: o,
					value: o
				}
			})
		}
	}
}
